package com.ufgov.agcfs.report.web;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import uap.iweb.exception.WebRuntimeException;
import uap.iweb.icontext.IWebViewContext;

import com.ufgov.agcfs.report.entity.Report;
import com.ufgov.agcfs.report.entity.ReportField;
import com.ufgov.agcfs.report.entity.RptTypeNode;
import com.ufgov.agcfs.report.service.ReportDesignService;


@Controller("report.reportController")
@Scope("prototype")
@RequestMapping(value = "/report")
public class ReportDesignController {
	private final Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private ReportDesignService reportService;
	
	/*@RequestMapping(method = RequestMethod.GET,value="getReportList")
	public  @ResponseBody HashMap<String,Object> getReportList(@RequestParam(value="start")int start,
			   @RequestParam(value="length")int length,
			   @RequestParam(value="draw")int draw,
			   HttpServletRequest request){
		try {
			Map<String,String> condMap = new HashMap<String, String>();
			String searchCond = request.getParameter("extra_search");
			if (!searchCond.equals("")){
				ObjectMapper mapper = new ObjectMapper();  
				condMap = mapper.readValue(searchCond,JSONObject.class);//转成map  
			}
			
			
			Map<String, String[]> paramHash= request.getParameterMap();
			Map<String,String> columnHash = new HashMap<String, String>();
			Map<String,String> sortHash = new LinkedHashMap<String, String>();
			for (Entry<String, String[]> entry : paramHash.entrySet()) {
				String key = entry.getKey();
				String value = entry.getValue()[0];
				String columnIndex="";
				if ((value!=null)&&(!value.equals(""))){
					if (key.indexOf("][data]")>0){
						key = key.replace("][data]", "").replace("s[", "");
						columnHash.put(key, value);
					}else if ((key.indexOf("order[")>=0)&&
							  (key.indexOf("column")>=0)){
						columnIndex = value;
						key = key.replace("column", "dir");
						if (paramHash.containsKey(key)){
							value = paramHash.get(key)[0];
							sortHash.put("column"+columnIndex, value);
						}
					}
				}	
			}
			
			List<Report> reptList = reportService.getReportList(start,length,columnHash,
										sortHash,condMap);
			int repCnt = reptList.size();
			HashMap<String,Object> hashRet = new HashMap<String, Object>();
			hashRet.put("draw", draw);
			hashRet.put("recordsTotal",repCnt);
			hashRet.put("recordsFiltered",repCnt);
			hashRet.put("data",reptList);
			return hashRet;
		} catch (Exception e) {
			logger.error(e.getMessage());
			IWebViewContext.getResponse().write("false");
			throw new WebRuntimeException("查询数据失败!");
		}		
	}*/
	
	@RequestMapping(method = RequestMethod.GET,value="getReportList")
	public  @ResponseBody Map<String,Object> getReportList(HttpServletRequest request){
		try {
			Map<String,String> condMap = new HashMap<String, String>();
			Map<String,Object> hashRet = new HashMap<String, Object>();
			String searchCond = request.getParameter("extra_search");
			if ((searchCond!=null)&&(!searchCond.equals(""))){
				ObjectMapper mapper = new ObjectMapper();  
				condMap = mapper.readValue(searchCond,JSONObject.class);//转成map 
				List<Report> reptList = reportService.getReportList(condMap);
				hashRet = new HashMap<String, Object>();
//				hashRet.put("options", new ArrayList());
//				hashRet.put("files",new ArrayList());
				hashRet.put("data",reptList);
			}
			return hashRet;
		} catch (Exception e) {
			logger.error(e.getMessage());
			IWebViewContext.getResponse().write("false");
			throw new WebRuntimeException("查询数据失败!");
		}		
	}
	
	@RequestMapping(method = RequestMethod.GET,value="getRptType")
	public @ResponseBody List<RptTypeNode> getReportTypeList(HttpServletRequest request){
		try {
			String nd = request.getParameter("nd");
			if ((nd!=null)&&(!nd.equals(""))){
				return reportService.getRptTypeByND(nd);
			} else
				return reportService.getRptTypeNodes();
		} catch (Exception e) {
			logger.error(e.getMessage());
			IWebViewContext.getResponse().write("false");
			throw new WebRuntimeException("查询数据失败!");
		}		
	}
	
	@RequestMapping(method = RequestMethod.POST,value="saveReport")
	public @ResponseBody Map<String, String> saveReport(@RequestBody Report report){
		Map<String, String> resultMap = new HashMap<String, String>();
		resultMap.put("result", "success");
		resultMap.put("reason", "保存成功！");
		try {
			reportService.saveReport(report,resultMap);
		} catch (Exception e) {
			logger.error(e.getMessage());
			resultMap.put("result", "fail");
			resultMap.put("reason", "保存失败，请稍后重试！");
		}
		return resultMap;		
	}
	
	
	@RequestMapping(method = RequestMethod.POST,value="deleteReports")
	public @ResponseBody Map<String, String> deleteReport(HttpServletRequest request){
		Map<String, String> resultMap = new HashMap<String, String>();
		resultMap.put("result", "success");
		resultMap.put("reason", "保存成功！");
		try {
			String[] ids = request.getParameter("ids").split(",");
			List<String> reptIds = new ArrayList<String>();
			Collections.addAll(reptIds, ids);
			reportService.deleteReports(reptIds , resultMap);
		} catch (Exception e) {
			logger.error(e.getMessage());
			resultMap.put("result", "fail");
			resultMap.put("reason", "保存失败，请稍后重试！");
		}
		return resultMap;		
	}
	
	@RequestMapping(method = RequestMethod.GET,value="getRptFldList")
	public @ResponseBody Map<String, Object> getRptFldList(HttpServletRequest request){
		try {
			Map<String,Object> hashRet = new HashMap<String, Object>();
			String nd = request.getParameter("nd");
			String rptCode = request.getParameter("rptcode");
			if ((nd!=null)&&(!nd.equals(""))&&(rptCode!=null)&&(!rptCode.equals(""))){
				Report report = new Report();
				report.setNd(nd);;
				report.setReportCode(rptCode);
				List<ReportField> rptFldList = reportService.getRptFldList(report);
				hashRet = new HashMap<String, Object>();
				hashRet.put("data",rptFldList);
			}
			return hashRet;
		} catch (Exception e) {
			logger.error(e.getMessage());
			IWebViewContext.getResponse().write("false");
			throw new WebRuntimeException("查询数据失败!");
		}		
	}
}
